package com.ztom.top100;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 字符串解码
 * <p>
 * https://leetcode-cn.com/problems/decode-string/
 *
 * @author ZhangTao
 */
public class Code84DecodeString {

    public String decodeString(String s) {
        if (s == null || s.length() == 0) {
            return null;
        }

        char[] chars = s.toCharArray();
        // 记录数字
        Deque<Integer> numStack = new LinkedList<>();
        // 记录字母
        Deque<String> charStack = new LinkedList<>();
        // 用于读取数字
        int num = 0;
        // 用于读字母串
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                // 是数字, 入数字栈
                num = num * 10 + Integer.parseInt(chars[i] + "");
            } else if (chars[i] == '[') {
                // 数字入栈
                numStack.addLast(num);
                num = 0;

                // 之前的字母串先入栈
                charStack.addLast(sb.toString());
                // 准备收集当前 [] 内的字母串
                sb.setLength(0);
            } else if (chars[i] == ']') {
                // 结算当前 [] 的字母串
                Integer count = numStack.pollLast();
                StringBuilder tmp = new StringBuilder();
                for (int k = 0; k < count; k++) {
                    tmp.append(sb);
                }
                sb.setLength(0);
                sb.append(charStack.pollLast()).append(tmp);
            } else {
                // 收集字母串
                sb.append(chars[i]);
            }
        }
        return sb.toString();
    }
}
